package com.gitee.wsl.common.ui.input.event

import com.gitee.wsl.common.ui.base.Point
import com.gitee.wsl.common.ui.input.KEventListener
import com.gitee.wsl.common.ui.input.emptyListener

@ExperimentalKEvent
class KZoomEvent(
    val startZoomPos: Point,
    val deltaX: Double,
    val deltaY: Double,
    private val hasMetaKeys: HasMetaKeys = HasMetaKeysImpl()
) : KEvent, HasMetaKeys by hasMetaKeys {

     constructor(startZoomPos: Point, delta: Double, hasMetaKeys: HasMetaKeys = HasMetaKeysImpl()) : this(startZoomPos, delta, delta, hasMetaKeys)

     companion object {

         const val diffTimeBetweenZoomEventsToDetectRestart: Int = 200

         fun isNewZoom(currentTime: Double, lastTime: Double?): Boolean =
            if (lastTime == null) {
                true
            } else {
                currentTime - lastTime > diffTimeBetweenZoomEventsToDetectRestart
            }

         fun isNewZoom(currentTime: Long, lastTime: Long?): Boolean =
            if (lastTime == null) {
                true
            } else {
                currentTime - lastTime > diffTimeBetweenZoomEventsToDetectRestart
            }

         const val minDelta: Double = -100.0
         const val maxDelta: Double = 100.0

         fun scaleDelta(
             currentDelta: Double,
             originMinDelta: Double,
             originMaxDelta: Double,
             newMinDelta: Double = minDelta,
             newMaxDelta: Double = maxDelta
        ): Double {
            val originBoundsSize = originMaxDelta - originMinDelta
            val currentDeltaPercentInBounds = (currentDelta - originMinDelta) / originBoundsSize

            val newBoundsSize = newMaxDelta - newMinDelta
            var newDeltaValue = newMinDelta + newBoundsSize * currentDeltaPercentInBounds

            if (newDeltaValue > maxDelta) {
                newDeltaValue = maxDelta
            }

            if (newDeltaValue < minDelta) {
                newDeltaValue = minDelta
            }

            return newDeltaValue
        }
    }

    override fun toString(): String {
        return "KZoomEvent(startZoomPos=$startZoomPos, deltaX=$deltaX, deltaY=$deltaY)"
    }

}

@ExperimentalKEvent
//internal expect fun zoomEventsListener(): KEventListener<KZoomEvent>


@OptIn(ExperimentalKEvent::class)
fun zoomEventsListener(): KEventListener<KZoomEvent> = emptyListener()